//
//  DeviceInfo.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/6.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "DeviceInfo.h"
#import "LGBluetooth.h"

@implementation DeviceInfo

+ (NSString *)primaryKey {
    return @"indefinitelyKey";
}

+ (DeviceInfo *)devicePrivateKey:(NSString *)macAddress withUserId:(NSString *)userId {
    if (macAddress.length == 0 || userId == 0) {
        return nil;
    }
   
    RLMRealm *realm = [RLMRealm defaultRealm];
    NSString *key = [NSString stringWithFormat:@"%@_%@",userId,macAddress];
    DeviceInfo *deviceInfo = [DeviceInfo objectForPrimaryKey:key];
    if (deviceInfo == nil) {
        deviceInfo = [[DeviceInfo alloc] init];
        deviceInfo.indefinitelyKey = key;
        deviceInfo.macAddress = macAddress;
    }
    [realm beginWriteTransaction];
    [realm addObject:deviceInfo];
    if (![[User userWithPrivateKey:userId].lastDeviceMac isEqualToString:macAddress]) {
        deviceInfo.isNewChangeConnect = YES;
    }
    [realm commitWriteTransaction];
    return deviceInfo;
}

+ (DeviceInfo *)getLastDevice {
    User *user = [User getLastUser];
    if (user.lastDeviceMac) {
       return [DeviceInfo devicePrivateKey:user.lastDeviceMac withUserId:user.userID];
    }
    return nil;
}

+ (DeviceInfo *)deviceWithPer:(LGPeripheral *)per {
    User *user = [User getLastUser];
    DeviceInfo *device = [DeviceInfo devicePrivateKey:user.lastDeviceMac withUserId:user.userID];
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        user.lastDeviceMac = per.macAddress;
        device.deviceUUID = per.UUIDString;
        device.oemType = per.oemType;
    }];
    return device;
}

@end
